/**
 ****************************************************************
 * Copyright (c) 2011 –苏州埃涅加克电子信息科技有限公司
 * Title: wmb.MD5Util
 * Description: 加密解密算法
 **************************************************************** 
 * 2011-12-02  V1.0  Li CaiRong    New Files for MD5加密算法
 */

package com.engc.common.utils;

import java.io.InputStream;
import java.io.Serializable;
import java.net.URLDecoder;

import org.apache.commons.lang.StringUtils;


public class PhotoUtil implements Serializable {

	private static MessageManager ftpProperties = new MessageManager("ftp");
	private static String host = ftpProperties.getMessage("photo_ftp_host");
	private static Integer port = Integer.parseInt(ftpProperties.getMessage("photo_ftp_port"));
	private static String userName = ftpProperties.getMessage("photo_ftp_user");
	private static String pwd = ftpProperties.getMessage("photo_ftp_pwd");
	/**
	 * 获取绝对路径地址
	 * foldername 本地文件保存的文件夹名称 列：logo
	 */
	public static String getRealPath(String foldername) throws Exception {
		String bastPath = PhotoUtil.class.getResource("").getPath();
		bastPath = URLDecoder.decode(bastPath, "utf-8");// 关键啊 ！
		String filePath = bastPath.substring(0,bastPath.indexOf("WEB-INF"));
		filePath = filePath.substring(1, filePath.length()-1);
		return filePath+"/"+Constant.PIC_PREFIX+foldername+"/";
	}

	/**
	 * 
	 * 下载图片
	 * imagename 图片名称 列：/logo/123456.jpg
	 * return 本地图片地址
	 * */
	public static String downloadimage(String imagename) throws Exception {
		if(imagename==null||StringUtils.isBlank(imagename)){
			return Constant.PIC_PREFIX + Constant.PIC_DEFAULT;
		}else{
			String foldername = imagename.split("/")[1];
			String filename = imagename.split("/")[2];
			FTPUtil ftpUtil = new FTPUtil();
			String remoteDir = ftpProperties.getMessage("photo_ftp_"+foldername);
			ftpUtil.setRemoteDir(remoteDir);
			//fullpath 文件全路径
			String fullPath = getRealPath(foldername);
			boolean c = ftpUtil.login(host,port, userName, pwd);
			if (!c) {
				return Constant.PIC_PREFIX + Constant.PIC_DEFAULT;
			}
			if(!ftpUtil.downloadNClose(filename, fullPath)){
				return Constant.PIC_PREFIX + Constant.PIC_DEFAULT;
			}
			return Constant.PIC_PREFIX + imagename;
		}
	}
	
	/**
	 * 
	 * 上传图片
	 * fis 文件流
	 * foldername 文件夹名称 如：logo
	 * filename 图片名称 列：123456.jpg
	 * return 本地图片地址
	 * */
	public static String uploadimage(InputStream fis,String foldername,String filename) throws Exception{
		String remoteDir = ftpProperties.getMessage("photo_ftp_"+foldername);
		FTPUtil ftpUtil = new FTPUtil();
		ftpUtil.setRemoteDir(remoteDir);
		boolean a = ftpUtil.login(host,port, userName, pwd);
		if (!a) {
			return null;
		}
		if(!ftpUtil.upload(fis, filename, remoteDir)){
			return null;
		}
		return "/"+foldername+"/"+filename;
	}
	
	
	public static void main(String args[])throws Exception{
		System.out.println(getRealPath("logo"));
	}
}
